package com.getee.tianchaohongyu.kopier.parser

import com.getee.tianchaohongyu.kopier.NodeData


/**
 * 属性解析器
 * created zpf on 2019/2/18 0018
 */
object PropertyParser : AbstractParser() {

    init {
        errorChars.add(')')
    }

    override fun parse(nodeData: NodeData, iterator: Iterator<Int>): NodeData {
        var comma = false
        loop@ do {
            val result = find(iterator, ',', '[', ']', '(')
            val property = NodeData(result.contents, nodeData.root, nodeData)

            //非根节点,表达式结束
            if (!result.have && nodeData != nodeData.root) {
                throw RuntimeException("提前结束:${nodeData.fullName}[${nodeData.properties.joinToString { it.toString() }} ${if(comma) "" else ","}${result.contents}")
            }

            //没有属性名输入
            if (result.contents.isEmpty() && !comma) throw java.lang.RuntimeException("需要属性名:${nodeData.fullName}[${nodeData.properties.joinToString { it.toString() }} 之后出现了意外字符: ${result.contents}${result.char}")
            if (result.contents.isNotEmpty() && comma) throw java.lang.RuntimeException("需要逗号:${nodeData.fullName}[${nodeData.properties.joinToString { it.toString() }} 之后出现了意外字符: ${result.contents}${result.char}")
            if (result.contents.isNotEmpty()) nodeData.properties.add(property)

            when (result.char) {
                ',' -> {
                    comma = false
                }
                '[' -> {
                    parse(property, iterator)
                    comma = true
                } //新进属性
                '(' -> {
                    PatternParser.parse(property, iterator)
                    comma = true
                }
                ']' -> break@loop
            }
        } while (result.have)
        return nodeData
    }
}